package com.babble.blog.config;

import lombok.Data;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * es搜索引擎配置类
 *
 * @author wm
 */
@Data
@Configuration
@ConfigurationProperties("spring.elasticsearch")
public class ElasticsearchConfig {
	private String schema;
	private String username;
	private String password;
	private String address;
	private Integer connectTimeout;
	private Integer socketTimeout;
	private Integer connectionRequestTimeout;
	private Integer maxConnectNum;
	private Integer maxConnectPerRoute;

	public static final RequestOptions COMMON_OPTIONS;

	static {
		// RequestOptions类保存了请求的部分，这些部分应该在同一个应用程序中的许多请求之间共享。
		// 创建一个singqleton实例，并在所有请求之间共享它。可以设置请求头之类的一些配置
		RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
		// builder.addHeader("Authorization", "Bearer " + TOKEN);
		// builder.setHttpAsyncResponseConsumerFactory(
		//         new HttpAsyncResponseConsumerFactory
		//                 .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 *1024));
		COMMON_OPTIONS = builder.build();
	}

	@Bean
	public RestHighLevelClient restHighLevelClient() {
		//拆分地址,集群使用
		List<HttpHost> httpHosts = new ArrayList<>();
		String[] hostList = address.split(",");
		for (String addr : hostList) {
			String host = addr.split(":")[0];
			String port = addr.split(":")[1];
			httpHosts.add(new HttpHost(host, Integer.parseInt(port), schema));
		}
		final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
		credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

		//转换成HttpHost数组
		HttpHost[] httpHost = httpHosts.toArray(new HttpHost[]{});
		//构建连接对象
		RestClientBuilder builder = RestClient.builder(httpHost);
		//异步连接延时配置
		builder.setRequestConfigCallback(requestConfigBuilder ->
			requestConfigBuilder.setConnectTimeout(connectTimeout)
				.setSocketTimeout(socketTimeout)
				.setConnectionRequestTimeout(connectionRequestTimeout)
		);
		//异步配置连接数配置
		builder.setHttpClientConfigCallback(httpAsyncClientBuilder ->
			httpAsyncClientBuilder.setMaxConnTotal(maxConnectNum)
				.setMaxConnPerRoute(maxConnectPerRoute)
				.setDefaultCredentialsProvider(credentialsProvider)
		);
		return new RestHighLevelClient(builder);
	}
}
